package pl.vegasoft.jpgtimename;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.Locale;

import javax.swing.text.DateFormatter;

import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.MetadataException;
import com.drew.metadata.exif.ExifDirectory;

public class JpgTimeName {
	
	public static void main(String[] args) throws MetadataException, ParseException {
		FileResolver resolver = new FileResolver();
		File[] filesToChange = resolver.getFiles();
		
		if (filesToChange.length == 0) {
			System.out.println("There are no files to change.");
			System.exit(1);
		}
		
		for(File file : filesToChange) {
			try {
				Metadata metadata = JpegMetadataReader.readMetadata(file);
				Directory directory = metadata.getDirectory(ExifDirectory.class);
				Date date  = directory.getDate(ExifDirectory.TAG_DATETIME);
				Locale plLocale = new Locale("pl", "PL");
				DateFormatter formatter = new DateFormatter(DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, plLocale));
				
				System.out.println("Renaming " + file.getAbsolutePath());
				
				file.renameTo(new File(file.getParentFile(), formatter.valueToString(date) + ".jpg"));
			} catch (JpegProcessingException e) {
				System.out.println("Looks like " + file.getAbsolutePath() + " is not a JPG");
			}
		}
	}

}
